'''
Created on Jun 13, 2010

iur - Universal Web Remote targetted for iphone
Copyright (C) 2010 forteresce@gmail.com

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

'''
from player.eventhandler import PlayerEventHandler
from model.song import Song
import dbus
from xl.trax import search
import re

class ExaileEventHandler(PlayerEventHandler):
    '''
    The event handler for Exaile player
    '''
    DBUS_NAME   = 'org.exaile.Exaile'
    EXAILE_DBUS_OBJECT = '/org/exaile/Exaile'
    
    def __init__(self):
        self.exaile = self.session_bus.get_object(self.DBUS_NAME, self.EXAILE_DBUS_OBJECT)
        pass
    
    def play(self):
        self.exaile.Play()
    
    def pause(self):
        self.exaile.PlayPause()

    def next(self):
        self.exaile.Next()

    def prev(self):
        self.exaile.Prev()
        
    def getCurrentSong(self):
        if not self.exaile.IsPlaying():
            return
        
        track = dict()
        
        # clean up
        vals = ('title','artist','album')
        for key in vals:
            track[key] = self.exaile.GetTrackAttr(key) if (self.exaile.GetTrackAttr(key) != 'None') else 'Unknown'
            
        return Song(track['title'], track['artist'], track['album'])

    def addSongToQueue(self, id):
        uri = base64.b64decode(id)
        self.exaile.Enqueue([uri])

    def volumeUp(self):
        self.exaile.ChangeVolume(dbus.Int32(10))
        return float(self.exaile.GetVolume())

    def volumeDown(self):
        self.exaile.ChangeVolume(dbus.Int32(-10))
        return float(self.exaile.GetVolume())

#====================================================================================================

from player.collectionhandler import PlayerCollectionHandler
from xl.collection import Collection
import os
from model.album import Album
import base64

class ExaileCollectionHandler(PlayerCollectionHandler):
    '''
    The collection handler for Exaile player
    '''
    DB_PATH = os.path.join(os.path.expanduser('~'), '.local', 'share', 'exaile', 'music.db')
    
    def __init__(self):
        self.collection = Collection("Exaile Collection", self.DB_PATH)
        
    def getAlbums(self, startsWith='a'):
        albumNames = set()

        for track in self.collection.tracks.itervalues():
            name = track.get_tag_display('album') 
            if name.lower().startswith(startsWith.lower()):
                albumNames.add(name)
        
        albums = []
        for name in albumNames:
            album = Album(base64.b64encode(name), name)
            albums.append(album)
        return albums

    def getSongsInAlbum(self, albumId):
        songs = []
        album = base64.b64decode(albumId)
        
        for result in search.search_tracks_from_string(self.collection, ('album==%s') % re.escape(album)):
            track = result.track
            title = track.get_tag_display('title', True, True, False)
            artist = track.get_tag_display('artist', True, True, False)
            location = track.get_tag_display('__loc', True, True, False)
            song = Song(title, artist, album, base64.b64encode(location))
            songs.append(song)
            
        return songs
